package edu.umn.contactviewer.task;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpUriRequest;

import android.net.http.AndroidHttpClient;
import android.os.AsyncTask;
import android.util.Log;

import com.google.gson.Gson;

import edu.umn.contactviewer.Contact;
import edu.umn.contactviewer.constant.ContactViewerConstants;
import edu.umn.contactviewer.datastore.DeleteContactRequestResponseListener;
import edu.umn.contactviewer.datastore.ContactListDataService.RequestResult;

public class DeleteContactsAsyncTask extends
		AsyncTask<String, Void, Boolean> {

	private static final String TAG = "DeleteContacts";
	private final Gson gson = new Gson();
	
	private Contact contactToDelete;
	private DeleteContactRequestResponseListener responseListener;

	// for GSON serialization
	public static class DeleteContactsResponse {

		private String status;
		private String message;

		public String getStatus() {
			return status;
		}

		public void setStatus(String status) {
			this.status = status;
		}

		public String getMessage() {
			return message;
		}

		public void setMessage(String message) {
			this.message = message;
		}
	}
	
	public DeleteContactsAsyncTask(Contact contactToDelete, DeleteContactRequestResponseListener responseListener) {
		
		this.contactToDelete = contactToDelete;
		this.responseListener = responseListener;
	}

	@Override
	protected Boolean doInBackground(String... arg0) {
		
		// Initialize to error response in case of exceptions.
		Boolean result = false;
		
		try {
			AndroidHttpClient client = AndroidHttpClient.newInstance("Android",
					null);
			HttpUriRequest request = new HttpDelete(
					ContactViewerConstants.WEB_SERVICE_URL
					+ ContactViewerConstants.SEPARATOR_SLASH
					+ contactToDelete.get_id()
					+ ContactViewerConstants.SEPARATOR_QUERY_STRING
					+ ContactViewerConstants.API_KEY_MAPPING); // Enhance URI for delete - contacts/<id>?key=greenzebras
			HttpResponse response = client.execute(request);
			InputStream in = response.getEntity().getContent();
			String jsonResponse = readJsonResponse(in);

			DeleteContactsResponse delContactsResponse = gson.fromJson(
					jsonResponse, DeleteContactsResponse.class);

			if (delContactsResponse.getStatus().equalsIgnoreCase("success")) {
				result = true;
			}

			client.close();

		} catch (IOException ex) {
			Log.e(TAG + "IO Exception: ", ex.toString());
		} catch (Exception ex) {
			Log.e(TAG + "Exception: ", ex.toString());
		}

		return result;
	}
	
	@Override
	protected void onPostExecute(Boolean result) {
		super.onPostExecute(result);
		
		RequestResult requestResult = RequestResult.FAIL;
		if (result) {
			requestResult = RequestResult.SUCCESS;
		}
		
		responseListener.onDeleteContactResponse(requestResult, this.contactToDelete);
	}

	private String readJsonResponse(InputStream in) throws IOException {
		String jsonResponse = "";
		BufferedReader buffer = new BufferedReader(new InputStreamReader(in));
		String s = "";
		while ((s = buffer.readLine()) != null) {
			jsonResponse += s;
		}
		buffer.close();

		return jsonResponse;
	}
}
